import { memo, FC, useRef, useState, useEffect } from 'react'
import { Modal, Form, Input, message, Button } from 'antd'
import type { FormInstance } from 'antd'
import { connect, Dispatch } from 'umi'
import './index.less'

interface IProps {
  visible: boolean
  hide: () => void
  dispatch: Dispatch
}
interface FormValues {
  [name: string]: any
}
const ForgetPassword: FC<IProps> = ({ visible, hide, dispatch }) => {
  const formRef = useRef<FormInstance>(null)
  const [count, setCount] = useState<number>(60)
  const timeRef = useRef<number | null>(null)
  const [isSend, setIsSend] = useState<boolean>(false)

  // 获取手机验证码
  const getCheckCode = () => {
    formRef.current?.validateFields(['phone'])
    const { phone } = formRef.current?.getFieldsValue(['phone'])
    dispatch({
      type: 'login/function_getSmsCode',
      payload: {
        phone
      },
      callback: (response) => {
        if (response.code == 200) {
          setIsSend(true)
          cutCount()
          timeRef.current = window.setInterval(cutCount, 1000)
          message.success('验证码获取成功')
        }
      }
    })
  }

  const cutCount = () => {
    setCount((prev) => prev - 1)
  }

  const handleOk = () => {
    formRef.current?.submit()
  }
  const handleCancel = () => {
    hide()
    formRef.current?.resetFields()
  }

  const onFinish = (values: FormValues) => {
    delete values.reNewPassword
    dispatch({
      type: 'login/function_forgetPassWord',
      payload: values,
      callback: (response) => {
        if (response.code === 200) {
          message.success('设置密码成功')
          handleCancel()
        }
      }
    })
  }

  useEffect(() => {
    if (count === 0) {
      clearInterval(timeRef.current!)
      setIsSend(false)
      setCount(60)
    }
  }, [count])
  useEffect(() => {
    if (!visible && timeRef.current) {
      clearInterval(timeRef.current!)
      setIsSend(false)
      setCount(60)
    }
  }, [visible])

  return (
    <>
      <Modal
        title="忘记密码"
        open={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        width="30%"
        okText="确认"
        cancelText="取消"
        maskClosable={false}
      >
        <Form
          name="basic"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          autoComplete="off"
          ref={formRef}
          onFinish={onFinish}
        >
          <Form.Item
            label="手机号"
            name="phone"
            rules={[
              {
                required: true,
                message: '请输入手机号!'
              },
              {
                pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
                message: '请输入正确格式的手机号码'
              }
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item
            label="验证码"
            name="smsCode"
            rules={[
              {
                required: true,
                message: '请输入验证码!'
              }
            ]}
          >
            <Input
              addonAfter={
                <Button
                  //判断如果点击了获取验证码，就让button按钮上显示 *秒后重发送 并且button设置为disabled
                  onClick={getCheckCode}
                  disabled={isSend}
                >
                  {isSend ? `${count}s后重新获取` : '获取验证码'}
                </Button>
              }
              placeholder="请输入验证码"
            />
          </Form.Item>
          <Form.Item
            label="新密码"
            name="password"
            rules={[
              { required: true, message: '请输入新密码!' },
              {
                pattern:
                  /((^(?=.*[a-z])(?=.*[A-Z])(?=.*[\W_])[\da-zA-Z\W_]{8,16}$)|(^(?=.*\d)(?=.*[A-Z])(?=.*[\W_])[\da-zA-Z\W_]{8,16}$)|(^(?=.*\d)(?=.*[a-z])(?=.*[\W_])[\da-zA-Z\W_]{8,16}$)|(^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[\da-zA-Z\W_]{8,16}$))/,
                message:
                  '请输入8-16位字符，至少包含数字、大写字母、小写字母、特殊字符中的三种类型'
              }
            ]}
          >
            <Input.Password placeholder="请输入新密码" />
          </Form.Item>
          <Form.Item
            label="确认新密码"
            name="reNewPassword"
            dependencies={['password']}
            rules={[
              { required: true, message: '确认新密码!' },
              ({ getFieldValue }) => ({
                validator(rule, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve()
                  }
                  return Promise.reject('新密码与确认新密码不同！')
                }
              })
            ]}
          >
            <Input.Password placeholder="确认新密码" />
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}

const mapStateToProps = () => {
  return {}
}

export default connect(mapStateToProps)(memo(ForgetPassword))
